<?php
namespace app\common\service;

use app\common\model\Product as ProductModel;
use think\Loader;

class Product{

    public function find($id){
        $productModel = new ProductModel();
        $product = $productModel ->find($id);
        return $product;
    }

    /**
     * 通过分类找到产品
     * @param $ids
     * @return $this
     */
    public function paginateByCats($ids,$pageSize = 20){
        $productModel = new ProductModel();
        $all = $productModel->whereIn('cat',$ids)->order('id desc')->paginate($pageSize);
        return $all;
    }

    public function paginate($pageSize = 20){

        $productModel = new ProductModel();

        $products = $productModel -> order('id desc')->paginate($pageSize);

        return $products;
    }


    public function all($ids){
        return ProductModel::all($ids);
    }



    public function insert($data){

        $productModel = new ProductModel();

        $validate = Loader::validate("ProductValidate");
        $checkResult = $validate ->scene("add") -> check($data);
        if(!$checkResult){
            return ['state'=>0,'message'=>$validate->getError()];
        }

        $result = $productModel->allowField(['name','shopid','price','desc','cover'])->save($data);
        $productData = ['content'=>isset($data['content'])?$data['content']:''];
        $productModel->productData()->save($productData);

        if(false === $result){

            return ['state'=>0,'message'=>$productModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$productModel->id];

    }


    public function update($data){
        $productModel = new ProductModel();

        if(intval($data['id']) <1){
            return ['state'=>0,'message'=>"参数错误"];
        }

        $validate = Loader::validate("ProductValidate");
        $checkResult = $validate ->scene('edit') -> check($data);
        if(!$checkResult){
            return ['state'=>0,'message'=>$validate->getError()];
        }

        $result = $productModel->allowField(['id','name','shopid','price','desc','cover'])->save($data,['id'=>intval($data['id'])]);
        $productModel = ProductModel::get($data['id']);
        $productModel -> productData ->content = isset($data['content'])?$data['content']:'';
        $productModel->productData->save();

        if(false === $result){
            return ['state'=>0,'message'=>$productModel->getError()];
        }

        return ['state'=>1,'message'=>''];
    }

    public function addPv($id){
        $product = ProductModel::get($id);
        $product->pv = intval($product->pv)+1;
        $product->save();
    }

    public function delete($id){
        $product = ProductModel::get($id);
        $result = $product->together("productData")->delete();

        return $result;
    }


}